<template>
  <a-drawer
    v-model:visible="isDrawer"
    :width="width"
    :title="title"
    unmountOnClose
    placement="right"
    ok-text="提交"
    :ok-loading="subLoading"
    :on-before-ok="formSubmit"
    @cancel="handleReset"
  >
    <a-form
      :model="formParams"
      :rules="rules"
      ref="formRef"
      label-placement="left"
      :label-width="80"
    >
      <a-form-item label="登录账号" field="username">
        <a-input
          placeholder="请输入登录账号"
          v-model="formParams.username"
          :disabled="formParams.userId ? true : false"
        />
      </a-form-item>
      <a-form-item label="所属部门" field="deptId">
        <a-tree-select
          :fieldNames="{
            key: 'deptId',
            title: 'deptName',
            children: 'children',
          }"
          :fallback-option="false"
          :data="deptList"
          clearable
          v-model="formParams.deptId"
          placeholder="请选择部门"
        />
      </a-form-item>
      <a-form-item label="密码" :field="!formParams.userId ? 'password' : ''">
        <a-input
          type="password"
          show-password-on="mousedown"
          placeholder="请输入密码"
          v-model="formParams.password"
        />
      </a-form-item>
      <a-form-item label="确认密码" :field="!formParams.userId ? 'passwordRe' : ''">
        <a-input
          type="password"
          show-password-on="mousedown"
          placeholder="请输入密码"
          v-model="formParams.passwordRe"
        />
      </a-form-item>

      <a-form-item label="角色" field="roleIds">
        <a-select
          clearable
          v-model="formParams.roleIds"
          :options="getRoleList"
          multiple
          placeholder="请选择角色"
        />
      </a-form-item>
      <a-form-item label="用户名" field="nickname">
        <a-input placeholder="请输入用户名" v-model="formParams.nickname" />
      </a-form-item>
      <a-form-item label="手机" field="mobile">
        <a-input placeholder="请输入手机" v-model="formParams.mobile" />
      </a-form-item>
      <a-form-item label="邮箱" field="email">
        <a-input placeholder="请输入邮箱" v-model="formParams.email" />
      </a-form-item>
      <a-form-item label="性别" field="sex">
        <a-radio-group v-model="formParams.sex" name="sexGroup">
          <a-space>
            <a-radio v-for="item in sexList" :key="item.dictValue" :value="item.dictLabel">
              {{ item.dictLabel }}
            </a-radio>
          </a-space>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="所在岗位" field="postId">
        <a-select
          :fieldNames="{ value: 'postId', label: 'postName' }"
          :options="postDataList"
          clearable
          multiple
          v-model="formParams.postId"
          placeholder="请选择所在岗位"
        />
      </a-form-item>
      <a-form-item label="个人介绍" field="remark">
        <a-textarea placeholder="请输入个人介绍" v-model="formParams.remark" />
      </a-form-item>
      <a-form-item label="是否启用" field="isEnable">
        <a-switch v-model="formParams.isEnable" />
      </a-form-item>
    </a-form>
  </a-drawer>
</template>

<script lang="ts" setup>
  import { ref, onMounted, computed } from 'vue';
  import { Message, SelectOptionData } from '@arco-design/web-vue';
  import type { formParamsType } from './types';
  import { useDictionary } from '@/hooks/web/useDictionary';

  import { addUsur, editUsur, userInfo } from '@/api/system/user';
  import { postList } from '@/api/common/index';
  import { deptTreeList } from '@/api/auth/dept';
  import { cloneDeep } from 'lodash-es';

  const rules: any = {
    username: {
      required: true,
      message: '登录账号不能为空',
      trigger: 'blur',
    },
    deptId: {
      required: true,
      message: '部门不能为空',
      trigger: 'change',
      type: 'number',
    },
    roleIds: {
      required: true,
      message: '角色不能为空',
      trigger: 'change',
      type: 'array',
    },
    password: {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    },
    passwordRe: {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    },
  };

  const emit = defineEmits(['change']);
  const { getDictTypeList } = useDictionary();

  const props = defineProps({
    title: {
      type: String,
      default: '添加用户',
    },
    width: {
      type: Number,
      default: 450,
    },
    roleList: {
      type: Array as PropType<SelectOptionData[]>,
    },
  });

  const sexList = ref<any[]>();
  const deptList = ref<any[]>();
  const postDataList = ref([]);
  const defaultValueRef = () => ({
    userId: undefined,
    roleIds: [],
    isEnable: true,
    deleteStatus: 1,
    deptId: undefined,
    email: '',
    mobile: '',
    nickname: '',
    password: '',
    passwordRe: '',
    remark: '',
    sex: '',
    username: '',
    postId: [],
  });

  const getRoleList = computed(() => {
    return props.roleList as SelectOptionData[];
  });

  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);

  const formParams = ref<formParamsType>(defaultValueRef());

  async function openDrawer(userId?) {
    const deptResList = await deptTreeList();
    deptList.value = deptResList;
    const postListRes = await postList();
    postDataList.value = postListRes;
    if (userId) {
      formParams.value.userId = userId;
      getInfo();
      return;
    }
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  function formSubmit(done) {
    formRef.value.validate((errors) => {
      if (errors) {
        Message.error('请填写完整信息');
        subLoading.value = false;
        return done(false);
      }
      // 克隆
      const params = cloneDeep(formParams.value);
      // 处理岗位
      if (Array.isArray(params.postId) && params.postId.length) {
        params.postId = params.postId.join(',');
      } else {
        params.postId = '';
      }
      // 处理部门
      if (params.deptId) {
        params.deptId = params.deptId + '';
      }
      if (params.password != params.passwordRe) {
        return Message.error('两次密码不一致');
      }
      const msg = params.userId ? '编辑成功' : '添加成功';
      if (params.userId) {
        editUsur(params)
          .then((_) => {
            Message.success(msg);
            emit('change');
            handleReset();
            return done(true);
          })
          .catch(() => {
            return done(false);
          });
      } else {
        addUsur(params)
          .then((_) => {
            Message.success(msg);
            emit('change');
            handleReset();
            return done(true);
          })
          .catch(() => {
            return done(false);
          });
      }
    });
  }

  function handleReset() {
    formRef.value.resetFields();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
    isDrawer.value = false;
  }

  function getInfo() {
    userInfo({ userId: formParams.value.userId }).then((res) => {
      const params = {
        userId: formParams.value.userId,
        deleteStatus: parseInt(res.deleteStatus),
        email: res.email,
        mobile: res.mobile,
        nickname: res.nickname,
        isEnable: res.isEnable,
        password: '',
        passwordRe: '',
        remark: res.remark,
        sex: res.sex,
        username: res.username,
        roleIds: res.roleIds,
        postId: res.postId ? res.postId.split(',').map(Number) : [],
        deptId: res.deptId || null,
      };
      formParams.value = Object.assign(formParams.value, params);
      isDrawer.value = true;
    });
  }

  onMounted(async () => {
    const list = await getDictTypeList({ dictType: 'sys_user_sex' });
    sexList.value = list;
  });

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
